import java.util.*;

public class Test1 {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> wordListSet = new HashSet<>();
        Set<String> oldWordSet = new HashSet<>();
        for (String s : wordList) {
            wordListSet.add(s);
        }
        if (!wordListSet.contains(endWord)) {
            return 0;
        }
        Queue<String> queue = new LinkedList<>();
        queue.add(beginWord);
        oldWordSet.add(beginWord);
        int step = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            step++;
            for (int k = 0; k < size; k++) {
                String tmp = queue.poll();
                for (int i = 0; i < tmp.length(); i++) {
                    char[] cc = tmp.toCharArray();
                    for (char j = 'a'; j <= 'z'; j++) {
                        cc[i] = j;
                        String change = new String(cc);
                        if (change.equals(endWord)) {
                            return step;
                        }
                        if (wordListSet.contains(change) && !oldWordSet.contains(change)) {
                            oldWordSet.add(change);
                            queue.add(change);
                        }
                    }
                }
            }
        }
        return 0;
    }
}
